//
//  SZCHotViewController.m
//  礼物说
//
//  Created by dllo on 16/4/19.
//  Copyright © 2016年 sunzhichao. All rights reserved.
//

#import "SZCHotViewController.h"

#define kHOTURL  [NSString stringWithFormat:@"http://api.liwushuo.com/v2/items?gender=1&generation=2&limit=50&offset=%@",page]

#define kGIFTURLCONTENTURL [NSString stringWithFormat:@"http://api.liwushuo.com/v2/item_subcategories/%@/items?limit=20&offset=%@",num, page]

@interface SZCHotViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain) BaseCollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *modelArr;
@property (nonatomic, retain) NSMutableArray *giftArr;
/** 页数*/
@property (nonatomic, assign) NSInteger n;
/** 哪一个网址id*/
@property (nonatomic, retain) NSNumber *decide;

@end

@implementation SZCHotViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}
- (void)dealloc {
    [_decide release];
    [_judge release];
    [_titles release];
    [_num release];
    [_giftArr release];
    [_modelArr release];
    [_collectionView release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [GiFHUD show];
    
    /** 热门大数组*/
    self.modelArr = [NSMutableArray array];
    self.decide = 0;
    self.giftArr = [NSMutableArray array];
    
    /**第三页的礼物 */
//    if ([_judge isEqualToString:@"giftContent"]) {
//        
//        self.navigationItem.title = _titles;
//        
//        UIBarButtonItem * rightGiftButton = [[UIBarButtonItem alloc] initWithImage: [UIImage imageNamed:@""] style:UIBarButtonItemStylePlain target:self action:@selector(rightGiftButtonAction)];
//        self.navigationItem.leftBarButtonItem = rightGiftButton;
//        [rightGiftButton release];
//        
//        
//        UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction)];
//        
//        
//        leftButton.tintColor = [UIColor whiteColor];
//        self.navigationItem.leftBarButtonItem = leftButton;
//        [leftButton release];
//        
//        [self dataHandles:_num Page:@"0"];
//        [self createCollection];
//        
//    }else {
    
        self.navigationItem.title = @"热门";
        self.navigationController.navigationBar.translucent = NO;
        /** 防止内置*/
        self.automaticallyAdjustsScrollViewInsets = NO;
        [self createCollection];
        [self dataHandlePage:@"0"];
//    }
}

//- (void)leftButtonAction {
//    
//}
//- (void)rightGiftButtonAction {
//    
//}

#pragma mark - 创建CollectionView
- (void)createCollection {
    
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 3;
    layout.minimumLineSpacing = 3;
    layout.itemSize = CGSizeMake(kWIDTHS(180), kHEIGHTS(260));
    layout.sectionInset = UIEdgeInsetsMake(3, 3, 3, 3);
    
    self.collectionView = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, kHEIGHT - 64) collectionViewLayout:layout];
//    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.pagingEnabled = NO;
    _collectionView.bounces = YES;
    [self.view addSubview:_collectionView];
    [_collectionView release];
    [layout release];
    
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerClass:[HotCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    [self createMjbfresh];
}

#pragma merk - 刷新
- (void)createMjbfresh{
    
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        if ([_judge isEqualToString:@"giftContent"]) {
            [self dataHandles:_num Page:@"0"];
        }else{
            [self dataHandlePage:@"0"];
        }
    }];
    self.n = 0;
    _collectionView.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
        _n = _n + 50;
        NSString * str = [NSString stringWithFormat:@"%ld", (long)_n];
        if ([_judge isEqualToString:@"giftContent"]) {
            [self dataHandles: _num Page:str];
        }else{
            [self dataHandlePage:str];
        }
    }];
}

#pragma mark - 数据解析
- (void)dataHandlePage:(NSString *)page {

    [XRAFNetworkTool GETUrl:kHOTURL body:nil headFile:nil response:XRJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        NSArray * data = responseObject[@"data"][@"items"];
        
        NSMutableArray * array = [NSMutableArray array];
        for (NSDictionary * dic in data) {
            HotModel * model = [[HotModel alloc] init];
            [model setValuesForKeysWithDictionary:dic[@"data"]];
            [array addObject:model];
        }
        if ([page isEqualToString:@"0"]) {
            
            [_modelArr removeAllObjects];
            
        }
        
        [_modelArr addObjectsFromArray:array];
        
        if (_modelArr.count > 0) {
            
            [_collectionView reloadData];
        }
        
        [GiFHUD dismiss];
        /** 如果成功，就关闭上拉加载和下拉刷新*/
        [_collectionView.mj_header endRefreshing];
        [_collectionView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)dataHandles:(NSNumber *)num Page:(NSString *)page {
    
    [XRAFNetworkTool GETUrl:kGIFTURLCONTENTURL body:nil headFile:nil response:XRJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        NSArray *data = responseObject[@"data"][@"items"];
        NSMutableArray *array = [NSMutableArray array];
        array = [GifContentsModel modelHandleWithArray:data];
        if (_decide == nil) {
            /**判断不同页面的page，网址中的页数是第一页，则是下拉刷新*/
            if ([page isEqualToString:@"0"]) {
                /**删除如有数据 */
                [self.giftArr removeAllObjects];
            }
            /**如果是同一个页面，不同的page则添加数组 */
            [self.giftArr removeAllObjects];
        }else {
            /**如果不同则刷新数组 */
            self.giftArr = array;
            /**将当前页面赋给下一个页面 */
            _decide = num;
        }
        if (_giftArr.count > 0) {
            [_collectionView reloadData];
        }
        [GiFHUD dismiss];
        /**如果成功，我们就关闭上拉加载和下拉刷新 */
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if ([_judge isEqualToString:@"giftContent"]) {
        return _giftArr.count;
    }else {
        return _modelArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    if ([_judge isEqualToString:@"giftContent"]) {
        cell.giftModel = _giftArr[indexPath.row];
        return cell;
    }else {
        cell.model = _modelArr[indexPath.row];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HotContentViewController *hotVc = [[HotContentViewController alloc] init];
    if ([_judge isEqualToString:@"giftContent"]) {
        GifContentsModel *model = _giftArr[indexPath.row];
        hotVc.num = model.number;
    }else {
        HotModel *model = _modelArr[indexPath.row];
        hotVc.num = model.number;
    }
    [self.navigationController pushViewController:hotVc animated:YES];
    [hotVc release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
